<template>
  <base-page-view class-name="page-container address-manage-container">
    <view style="height:20rpx;"></view>
    <view class="address-box first">
      <view class="row" :class="{ active: focus.name }">
        <input v-model="addressData.name" class="input" type="text" placeholder="请填写收货人" placeholder-class="placeholder" maxlength="7" @focus="focus.name = true" @blur="focus.name = false" />
      </view>
      <view class="row" :class="{ active: focus.mobile }">
        <input v-model="addressData.mobile" class="input" type="number" maxlength="11" placeholder="请填写联系电话" placeholder-class="placeholder" @focus="focus.mobile = true" @blur="focus.mobile = false" />
      </view>
      <view class="row" @tap="toggleTab()">
        <text class="input" :class="{'input-none': !addressData.province}">
          {{ addressData.province ? addressData.areaName : '请选择省市区' }}
        </text>
        <view>
          <image class="rightIcon" src="/static/images/mine/ic_mine_arror.png"></image>
        </view>
      </view>
      <view class="row row-two" :class="{ active: focus.detail }">
        <textarea v-model="addressData.detail" class="textarea" placeholder="请填写详细地址（街道、楼牌号等）" placeholder-class="placeholder" @focus="focus.detail = true" @blur="focus.detail = false" />
      </view>
    </view>
    <view v-if="manageType === 'add'" class="address-box">
      <view class="title">智能填写</view>
      <view class="bg-paste">
        <textarea :value="addressStr" placeholder-style="color:#CBCBCB" maxlength="200" placeholder="粘贴地址信息，可自动识别并填写如：碧粉，188**********，福建省 厦门市 xx区 xx街道 xxxxx" @input="addressStrInput" />
        <view class="right" @click="btnClick">
          <image v-if="addressStr" class="icon" src="/static/images/icon/icon_clear.png" mode="aspectFit" />
          <template v-else>粘贴</template>
        </view>
      </view>
      <view class="fun-footer">
        <view class="btn" @click="generateAddress">识别</view>
      </view>
    </view>
    <view class="address-box">
      <view class="row default-row">
        <text class="tit">设置为默认收货地址</text>
        <switch :checked="addressData.is_default" color="#000" @change="switchChange" />
      </view>
    </view>
    <!-- #ifdef MP-WEIXIN -->
    <view class="async" @click="syncAddress">
      <image class="icon" src="/static/images/mine/ic_mine_sync.png"></image>
      <b-text>同步微信收货地址</b-text>
    </view>
    <!-- #endif -->
    <address-picker
      :show="showAddressPicker"
      key-str="name"
      :default-data="[addressData.province,addressData.city,addressData.area]"
      @close="showAddressPicker = false"
      @confirm="onConfirm" />
    <view class="btnColumn">
      <view
        v-if="manageType === 'edit'"
        class="address_delete"
        @click="deleteAddress">
        删除
      </view>
      <view :class="{'address_save':manageType === 'edit','address_save_two':manageType !== 'edit'}" @click="confirm">
        保存
      </view>

    </view>
  </base-page-view>
</template>

<script>
import addressPicker from './address-picker/index.vue'
import { getClipboardData } from '@/utils/tools'
export default {
  components: {
    addressPicker
  },
  data() {
    return {
      manageType: '',
      showAddressPicker: false,
      focus: {
        name: false,
        mobile: false,
        detail: false
      },
      addressData: {
        name: '',
        mobile: '',
        province: '',
        city: '',
        area: '',
        country: '',
        detail: '',
        areaName: '',
        is_default: false
      },
      addressStr: '',
    }
  },
  onLoad(option) {
    let title = '新增收货地址'
    if (option.type === 'edit') {
      title = '编辑收货地址'
      this.addressData = JSON.parse(decodeURIComponent(option.addressData))
      console.log(this.addressData)
      this.addressData.is_default = Boolean(this.addressData.is_default)
    }
    this.addressData.areaName = this.addressData.province + this.addressData.city + this.addressData.area
    this.manageType = option.type
    this.$setNavTitle(title)
  },
  methods: {
    switchChange(e) {
      this.addressData.is_default = e.detail.value
    },
    addressStrInput(e) {
      this.addressStr = e.detail.value
    },
    btnClick() {
      if (this.addressStr) {
        this.addressStr = ''
      } else {
        getClipboardData(res => {
          if (res && res !== ' ') {
            this.addressStr = res
          }
        })
      }
    },
    async generateAddress() {
      const res = await this.$api.mineApi.generateAddress({ text: this.addressStr })
      if (res.success && res.data) {
        const { error_message, shipping_address } = res.data
        if (error_message) {
          uni.showToast({ title: error_message, icon: 'none', duration: 2000 })
        } else {
          this.addressData = {
            ...shipping_address,
            areaName: shipping_address.province + shipping_address.city + shipping_address.area
          }
        }
      }
    },
    // 提交
    async confirm() {
      const data = Object.assign({}, this.addressData)
      if (!data.name) {
        uni.showToast({
          title: '请填写收货人姓名',
          icon: 'none',
          duration: 2000
        })
        return
      }
      let nameValid = true
      for (let i = 0; i < data.name.length; i++) {
        var temp = data.name[i].charCodeAt()
        if (temp >= 48 && temp <= 57) {
          nameValid = false
          break
        }
      }
      if (!nameValid) {
        uni.showToast({
          title: '收货人不能包含数字',
          icon: 'none',
          duration: 2000
        })
        return
      }
      if (!/^\d{1,11}$/.test(data.mobile)) {
        uni.showToast({
          title: '请输入正确的手机号码',
          icon: 'none',
          duration: 2000
        })
        return
      }
      if (!data.province) {
        uni.showToast({
          title: '请选择省市区',
          icon: 'none',
          duration: 2000
        })
        return
      }
      if (!data.detail) {
        uni.showToast({
          title: '请填写门牌号信息',
          icon: 'none',
          duration: 2000
        })
        return
      }
      let res
      data.is_default = Number(data.is_default)
      if (this.manageType === 'edit') {
        res = await this.$api.mineApi.setShippingAddress(data)
      } else {
        res = await this.$api.mineApi.addShippingAddress(data)
      }
      if (res.success) {
        uni.showToast({
          title: `地址${this.manageType === 'edit' ? '修改' : '添加'}成功`,
          icon: 'none',
          duration: 1500
        })
        if (this.$prePage() && this.$prePage().resetUp) {
          this.$prePage().resetUp()
        }
        setTimeout(() => {
          uni.navigateBack()
        }, 800)
      }
    },
    toggleTab() {
      this.showAddressPicker = true
    },
    async deleteAddress() {
      const _this = this
      this.$gc.$message({
        title: '温馨提示',
        showMessage: true,
        align: 'center',
        content: '是否要删除该收货地址？',
        async confirm() {
          const res = await this.$api.mineApi.deleteShippingAddress(_this.addressData)
          if (res.success) {
            uni.showToast({
              title: `地址删除成功`,
              icon: 'none',
              duration: 1500
            })
            this.$prePage().resetUp()
            setTimeout(() => {
              uni.navigateBack()
            }, 800)
          }
        }
      })
    },
    syncAddress() {
      const _this = this
      uni.chooseAddress({
        success(res) {
          _this.addressData.name = res.userName
          _this.addressData.country = '中国'
          _this.addressData.province = res.provinceName
          _this.addressData.city = res.cityName
          _this.addressData.area = res.countyName
          _this.addressData.detail = res.detailInfo
          _this.addressData.areaName = res.provinceName + res.cityName + res.countyName
          _this.addressData.mobile = res.telNumber
        }
      })
    },
    onConfirm(data) {
      this.addressData.areaName = data[0].name + data[1].name + data[2].name
      this.addressData.province = data[0].name
      this.addressData.city = data[1].name
      this.addressData.area = data[2].name
      this.showAddressPicker = false
    }
  }
}
</script>

<style lang="scss" scoped>
  .address-box{
    // @include shadow();
    margin-bottom: 20rpx;
    // border-radius: 20rpx;
    overflow: hidden;
    padding: 30rpx;
    background-color: #fff;

    &.first{
      padding: 0 30rpx;
    }
  }
  .async{
    @include flex();
    @include center;
    color: #52B260;
    margin-top: 80rpx;
    font-size: 28rpx;
    .icon{
      margin-right: 20rpx;
      width: 28rpx;
      height: 28rpx;
    }
  }
  .btnColumn{
    // left: 30rpx;
    position: absolute;
    bottom: 30rpx;
    width: 100%;
    .address_delete{
      width:320rpx;
      height: 68rpx;
      line-height: 68rpx;
      text-align: center;
      color: #fff;
      background-color: #ccc;
      border-radius: 5rpx;
      float: left;
      margin-left: 30rpx;
    }
    .address_save{
      width:320rpx;
      height: 68rpx;
      line-height: 68rpx;
      text-align: center;
      color: #fff;
      background-color: #000;
      border-radius: 5rpx;
      float: right;
      margin-right: 30rpx;
    }
    .address_save_two{
      width: 90%;
      height: 88rpx;
      line-height: 88rpx;
      text-align: center;
      color: #fff;
      background-color: #000;
      border-radius: 5rpx;
      margin: 0 auto;
    }
  }
	.row{
		display: flex;
		align-items: center;
		position: relative;
		height: 110rpx;
		background: #fff;
    border-bottom: 1rpx solid $color-border;

    &.row-two{
      height: 150rpx;
    }
    &:nth-last-child(1){
      border: none;
    }
    &:not(:last-child).active{
      border-bottom: 1rpx solid #000;
    }

		.tit{
			flex-shrink: 0;
      width: 120rpx;
      font-weight: bold;
			font-size: 28rpx;
      color: #333333;
		}
		.input{
			flex: 1;
      font-size: 30rpx;
    }
    .textarea{
      font-size: 30rpx;
      width: 100%;
      height: 80rpx;
      line-height: 40rpx;
    }
    .uni-input-placeholder,
    .input-none{
      color: #999999;
    }
    .rightIcon{
      width: 13rpx;
      height: 22rpx;
    }
  }
  .bg-paste{
    @include flex;
    @include a-center;
    margin-top: 20rpx;
    padding: 16rpx 20rpx;
    background: #F5F5F5;
    textarea{
      @include sub-item;
      font-size: 28rpx;
      height: 150rpx;
    }
    .right{
      @include flex;
      @include center;
      font-size: 32rpx;
      width: 124rpx;
      padding: 12rpx 0;
      border-left: 1rpx solid #999;
      margin-left: 12rpx;

      .icon{
        width: 30rpx;
        height: 30rpx;
        display: block;
      }
    }
  }
  .fun-footer{
    text-align: right;
    margin-top: 24rpx;
    .btn{
      color: #fff;
      font-size: 28rpx;
      width: 160rpx;
      text-align: center;
      line-height: 64rpx;
      background: #000;
      border-radius: 5rpx;
      display: inline-block;
    }
  }
	.default-row{
    padding: 0;
    height: 50rpx;
		.tit{
			flex: 1;
		}
		switch{
			transform: translateX(16rpx) scale(.9);
		}
	}
	.save-btn{
		display: flex;
		align-items: center;
		justify-content: center;
		width: 690rpx;
		height: 80rpx;
		margin: 60rpx auto;
		color: #fff;
		border-radius: 10rpx;
		box-shadow: 1px 2px 5px rgba(25, 25, 25, 0.4);
	}
</style>
